package com.jmgd.cjlx.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jmgd.cjlx.constants.MainConstant;
import com.jmgd.cjlx.core.WdzHttp;
import com.jmgd.cjlx.dao.SendOrderMapper;
import com.jmgd.cjlx.dto.GoodsDto;
import com.jmgd.cjlx.dto.PaymentsDto;
import com.jmgd.cjlx.dto.SendOrderDto;
import com.jmgd.cjlx.entity.ExLogEntity;
import com.jmgd.cjlx.entity.SendOrder;
import com.jmgd.cjlx.param.ExSendOrderParam;
import com.jmgd.cjlx.param.FihSendOrderParam;
import com.jmgd.cjlx.service.PosService;
import com.jmgd.cjlx.service.WdzTokenService;
import com.ovopark.sdk.openplatform.GwInitRequestHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PosServiceImpl implements PosService {
    @Autowired
    WdzHttp wdzHttp;

    @Autowired
    SendOrderMapper sendOrderMapper;

    @Autowired
    WdzTokenService wdzTokenService;

    /**
     * @Author: Ligjian
     * @Date: 2022/4/16
     * @notes:发送销售单号
     */
    @Override
    @Async
    public String sendOrder(String dataType,String idNo)  {

        GwInitRequestHandler requestHandler = new GwInitRequestHandler();
        requestHandler.init();
        // 设置业务请求参数
        requestHandler.setParameter("orgId", MainConstant.wdz_orgId);
        requestHandler.setParameter("enterpriseId", MainConstant.wdz_enterpriseId);
//        SendOrderDto sendOrderDto = new SendOrderDto();
//
//        sendOrderDto.setCashierName("店员A");
//        sendOrderDto.setGuideNo("店员A");
//        sendOrderDto.setGuidePirce(new BigDecimal("1"));
//        sendOrderDto.setMachineId("001");
//        sendOrderDto.setPrice(new BigDecimal("1"));
//        sendOrderDto.setShopId("235");
//        sendOrderDto.setShopName("xiaomai");
//        sendOrderDto.setTicketId("918375201712191854034");
//        sendOrderDto.setTicketTimeStr("1513680844");
//        sendOrderDto.setVipCard("100001");
//
//        GoodsDto goodsDto = new GoodsDto();
//        goodsDto.setGoodsId("1111");
//        goodsDto.setGoodsName("薯片");
//        goodsDto.setPrice(new BigDecimal("1"));
//        goodsDto.setQuantity(new BigDecimal("1"));
//        goodsDto.setUnitPrice(new BigDecimal(("1")));
//        List goods = new ArrayList();
//        goods.add(goodsDto);
//
//        PaymentsDto paymentsDto = new PaymentsDto();
//        paymentsDto.setPaymentName("--");
//        paymentsDto.setPaymentType("--");
//        paymentsDto.setPrice(new BigDecimal("1"));
//        List payments = new ArrayList();
//        payments.add(paymentsDto);
//
//
//        sendOrderDto.setGoods(goods);
//        sendOrderDto.setPayments(payments);
//
//        String iposJson = JSONObject.toJSON(sendOrderDto).toString();
//
//        System.out.println(iposJson);

//
//        requestHandler.setParameter("iposJson", "{\n" +
//                "\t\"receive\": 2,\n" +
//                "\t\"guideNo\": \"\",\n" +
//                "\t\"change\": 0,\n" +
//                "\t\"guideId\": null,\n" +
//                "\t\"shopName\": \"xiaomai\",\n" +
//                "\t\"machineId\": \"001\",\n" +
//                "\t\"ticketTimeStr\": \"1513680844\",\n" +
//                "\t\"price\": 2,\n" +
//                "\t\"guidePrice\": 2,\n" +
//                "\t\"cashierId\": null,\n" +
//                "\t\"shopId\": \"235\",\n" +
//                "\t\"vipCard\": \"18662250114\",\n" +
//                "\t\"cashierName\": \"店员A\",\n" +
//                "\t\"ticketId\": \"9183752017121918540345\",\n" +
//                "\t\"refund\": 0,\n" +
//                "\t\"goods\": [{\n" +
//                "\t\t\"unitPrice\": 2,\n" +
//                "\t\t\"quantity\": 1,\n" +
//                "\t\t\"goodsId\": 33,\n" +
//                "\t\t\"price\": 2,\n" +
//                "\t\t\"guidePrice\": 2,\n" +
//                "\t\t\"goodsName\": \"百事可乐\"\n" +
//                "\t}],\n" +
//                "\t\"payments\": [{\n" +
//                "\t\t\"paymentType\": \"1\",\n" +
//                "\t\t\"paymentName\": \"现金\",\n" +
//                "\t\t\"price\": 15.2\n" +
//                "\t}]\n" +
//                "}");
        String function = "open.ovopark.pos.sendOrder";
        String version = "v3";
        //return wdzHttp.wdzhttp(requestHandler, version, function);

        List<SendOrder> sendOrderList = sendOrderMapper.selectSendOrder(dataType,idNo);
        String saleNo = "";
        SendOrderDto sendOrderDto1 = null;
        List goods1 = null;
        String uploadWareFlag = null;
        String amountWareFlag = null;
        String customerFlag = null;
        GoodsDto goodsDto1 = null;
        PaymentsDto paymentsDto = null;
        List payments1 = null;
        String resContent = null;
        String resultFlag = null;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;

        try{
        String token = wdzTokenService.getToken();

        for(SendOrder sendorder:sendOrderList){
            uploadWareFlag = sendorder.getUploadWareFlag();
            amountWareFlag = sendorder.getUploadAmountFlag();
            customerFlag = sendorder.getUploadCustomerFlag();

            if(!sendorder.getSaleNo().equals(saleNo)){
                if(sendOrderDto1!=null){
                    sendOrderDto1.setGoods(goods1);
                    //发送请求
                    //System.out.println("发送请求："+JSONObject.toJSON(sendOrderDto1).toString());
                    requestHandler.setParameter("iposJson",JSONObject.toJSON(sendOrderDto1).toString());
                    resContent = wdzHttp.wdzhttp(requestHandler, version, function,token);
                    JSONObject jsonObjectParent = JSON.parseObject(resContent);
                    resultFlag = jsonObjectParent.get("result").toString();
                    //System.out.println("返回成功："+resContent);
                    if(resultFlag.equals("成功")) {
                        FihSendOrderParam fihSendOrderParam = new FihSendOrderParam();
                        fihSendOrderParam.setDataType(dataType);
                        fihSendOrderParam.setSaleNo(sendOrderDto1.getTicketId());
                        fihSendOrderParam.setSaleIdNo(sendOrderDto1.getSaleIdNo());
                        //fihSendOrderParam.setRowno(sendOrderDto1.getRowno());
                        fihSendOrderParam.setIdNo(idNo);
                        sendOrderMapper.uploadFinish(fihSendOrderParam);
                    }else{
                        ExSendOrderParam exSendOrderParam = new ExSendOrderParam();
                        exSendOrderParam.setErrorMsg(resultFlag);
                        exSendOrderParam.setErrorParam(JSONObject.toJSON(sendOrderDto1).toString());
                        exSendOrderParam.setSaleNo(sendOrderDto1.getTicketId());
                        exSendOrderParam.setDataType(dataType);
                        exSendOrderParam.setIdNo(idNo);
                        //exSendOrderParam.setRowno(sendOrderDto1.getRowno());
                        exSendOrderParam.setSaleIdNo(sendOrderDto1.getSaleIdNo());
                        sendOrderMapper.exSendOrder(exSendOrderParam);
                    }
                    Thread.sleep(500);
                }
                sendOrderDto1 = new SendOrderDto();
                goods1 = new ArrayList();
                payments1 = new ArrayList();

                sendOrderDto1.setCashierName(sendorder.getCashierName());
                sendOrderDto1.setGuideNo(sendorder.getSalerName());

                sendOrderDto1.setMachineId("0");

                sendOrderDto1.setShopId(String.valueOf(sendorder.getBusno()));
                sendOrderDto1.setShopName(sendorder.getOrgname());
                sendOrderDto1.setTicketId(sendorder.getSaleNo());
                sendOrderDto1.setSaleIdNo(sendorder.getSaleIdNo());
                //sendOrderDto1.setRowno(sendorder.getRowNo());


                date = simpleDateFormat.parse(sendorder.getSaleDatetime());// 转为Date
                String unixTimestamp = String.valueOf(date.getTime()/1000);
                sendOrderDto1.setTicketTimeStr(unixTimestamp);
                sendOrderDto1.setVipCard(sendorder.getMembercardno());

                if(customerFlag.equals("1")) {
                    sendOrderDto1.setVipPhone(sendorder.getMemMobile());
                }

                goodsDto1 = new GoodsDto();
                if(uploadWareFlag.equals("1")) {
                    goodsDto1.setGoodsId(sendorder.getWareCode());
                    goodsDto1.setGoodsName(sendorder.getWaregeneralname());
                    goodsDto1.setQuantity(sendorder.getWareqty());
                    if(amountWareFlag.equals("1")) {
                        goodsDto1.setPrice(sendorder.getWareAmount());
                        goodsDto1.setUnitPrice(sendorder.getWarePrice());
                        goodsDto1.setGuidePrice(sendorder.getWareGuidePrice());
                        goodsDto1.setDiscount(goodsDto1.getGuidePrice().subtract(goodsDto1.getPrice()));
                    }
                    goods1.add(goodsDto1);
                }else{
                    goodsDto1.setGoodsId("*********");
                    goodsDto1.setGoodsName("*********");
                    goodsDto1.setQuantity(new BigDecimal("0"));

                    goodsDto1.setPrice(new BigDecimal("0"));
                    goodsDto1.setUnitPrice(new BigDecimal("0"));
                    goodsDto1.setGuidePrice(new BigDecimal("0"));
                    goodsDto1.setDiscount(new BigDecimal("0"));
                    goods1.add(goodsDto1);
                }

                //paymentsDto = new PaymentsDto();
                if(amountWareFlag.equals("1")) {
                    sendOrderDto1.setPrice(sendorder.getAmount());
                    sendOrderDto1.setGuidePrice(sendorder.getGuideAmount());
                }else{
                    sendOrderDto1.setGuidePrice(new BigDecimal("0"));
                    sendOrderDto1.setPrice(new BigDecimal("0"));
                }


            }else{
                goodsDto1 = new GoodsDto();
                if(uploadWareFlag.equals("1")) {
                    goodsDto1.setGoodsId(sendorder.getWareCode());
                    goodsDto1.setGoodsName(sendorder.getWaregeneralname());
                    goodsDto1.setQuantity(sendorder.getWareqty());
                    if(amountWareFlag.equals("1")) {
                        goodsDto1.setPrice(sendorder.getWareAmount());
                        goodsDto1.setUnitPrice(sendorder.getWarePrice());
                        goodsDto1.setGuidePrice(sendorder.getWareGuidePrice());
                        goodsDto1.setDiscount(goodsDto1.getGuidePrice().subtract(goodsDto1.getPrice()));
                    }
                    goods1.add(goodsDto1);
                }else{

                }
            }
            saleNo = sendorder.getSaleNo();
        }

        //补发最后一次
        if(sendOrderDto1!=null){
            sendOrderDto1.setGoods(goods1);
            //发送请求
            //System.out.println("发送请求："+JSONObject.toJSON(sendOrderDto1).toString());
            requestHandler.setParameter("iposJson",JSONObject.toJSON(sendOrderDto1).toString());
            resContent = wdzHttp.wdzhttp(requestHandler, version, function,token);
            JSONObject jsonObjectParent = JSON.parseObject(resContent);
            resultFlag = jsonObjectParent.get("result").toString();
            //System.out.println("返回成功："+resContent);
            if(resultFlag.equals("成功")) {
                FihSendOrderParam fihSendOrderParam = new FihSendOrderParam();
                fihSendOrderParam.setDataType(dataType);
                fihSendOrderParam.setSaleNo(sendOrderDto1.getTicketId());
                //fihSendOrderParam.setRowno(sendOrderDto1.getRowno());
                fihSendOrderParam.setSaleIdNo(sendOrderDto1.getSaleIdNo());
                fihSendOrderParam.setIdNo(idNo);
                sendOrderMapper.uploadFinish(fihSendOrderParam);
            }else{
                ExSendOrderParam exSendOrderParam = new ExSendOrderParam();
                exSendOrderParam.setErrorMsg(resultFlag);
                exSendOrderParam.setErrorParam(JSONObject.toJSON(sendOrderDto1).toString());
                exSendOrderParam.setSaleNo(sendOrderDto1.getTicketId());
                exSendOrderParam.setDataType(dataType);
                exSendOrderParam.setIdNo(idNo);
                //exSendOrderParam.setRowno(sendOrderDto1.getRowno());
                exSendOrderParam.setSaleIdNo(sendOrderDto1.getSaleIdNo());
                sendOrderMapper.exSendOrder(exSendOrderParam);
            }
            Thread.sleep(500);
        }
        }catch (Exception ex){
            ExLogEntity exLogEntity = new ExLogEntity();
            exLogEntity.setData_type("万店掌");
            exLogEntity.setParam_msg(JSONObject.toJSON(sendOrderDto1).toString());
            exLogEntity.setErr_msg(resContent);
            exLogEntity.setEx_msg(ex.getMessage());
            sendOrderMapper.insertExLog(exLogEntity);
        }
        return "success";
    }

    @Override
    public String delOrder(String beginDate, String endDate) throws ParseException {
        GwInitRequestHandler requestHandler = new GwInitRequestHandler();
        requestHandler.init();

        // 设置业务请求参数
        requestHandler.setParameter("orgId", MainConstant.wdz_orgId);
        requestHandler.setParameter("enterpriseId", MainConstant.wdz_enterpriseId);
        String function = "open.ovopark.pos.deleteOrder";
        String version = "v1";
        requestHandler.setParameter("startTime",beginDate);
        requestHandler.setParameter("endTime",endDate);

        String token = wdzTokenService.getToken();
        String resContent = wdzHttp.wdzhttp(requestHandler, version, function,token);

        JSONObject jsonObjectParent = JSON.parseObject(resContent);
        String resultFlag = jsonObjectParent.get("result").toString();
        //System.out.println("返回成功："+resContent);
        if(resultFlag.equals("成功")) {
            System.out.println("删除成功");
        }else{
            System.out.println("删除失败"+resContent);
        }
        return null;
    }
}
